﻿using System;
using System.Configuration;
using System.Web;
using System.IO;

namespace Shuba.Web.master
{
    public partial class negative_upload : basePage
    {
        string msg;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_NEGATIVE_FILE");
                if (!IsUserAdd(acl))
                {
                    msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }
                LabelTitle.Text = GetPageTitle("MSTR_NEGATIVE_FILE");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Boolean fileOK = false;
                string path = Server.MapPath("~/uploads/");
                string ErrMessage = "";
                int ErrLine = 0;

                if (FileUpload1.HasFile)
                {
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = { ".txt", ".csv" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;

                    string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(fName);

                    var filestream = File.OpenText(fName);
                    string contents = filestream.ReadToEnd();
                    filestream.Close();

                    var bllFile = new Business.NegativeFile();
                    Model.NegativeFileInfo Info;

                    char rowDelimiter = '\n';
                    char fldDelimiter = '\t';

                    //CultureInfo ci = new CultureInfo("id-ID");

                    var rows = contents.Split(rowDelimiter);
                    try
                    {
                        for (var i = 1; i < rows.Length; i++)
                        {
                            var fields = rows[i].Split(fldDelimiter);
                            if (fields.Length > 1)
                            {
                                if (!IsValidEntryFormat(fields[0].Trim(), "N")) ErrMessage = "<BR> Invalid Bank Code Value or Format at Column : 1, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[2].Trim(), "D")) ErrMessage = "<BR> Invalid Date of Birth Value or Format at Column : 3, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[5].Trim(), "N")) ErrMessage = "<BR> Invalid Customer ID Value or Format at Column : 6, Line :" + i.ToString();
                                //if (!IsValidEntryFormat(fields[6].Trim(), "N")) ErrMessage = "<BR> Invalid Account Number Value or Format at Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[9].Trim(), "M")) ErrMessage = "<BR> Invalid Amount Value or Format at Column : 10, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[11].Trim(), "D")) ErrMessage = "<BR> Invalid Date Value or Format at Column : 12, Line :" + i.ToString();

                                if (ErrMessage == "")
                                {
                                    Info = new Shuba.Model.NegativeFileInfo();

                                    try
                                    {
                                        Info.COD_BANK = fields[0].Trim() == "" ? 0 : Convert.ToInt32(fields[0].Trim());
                                        Info.COD_BANK_NAME = fields[1].Trim();
                                        Info.DAT_BIRTH_CUST = Convert.ToDateTime(fields[2].Trim());
                                        Info.IDENTITY_NO = fields[3].Trim();
                                        Info.COD_CC_HOMEBRN = fields[4].Trim();
                                        Info.COD_CUST_ID = fields[5].Trim() == "" ? 0 : Convert.ToInt32(fields[5].Trim().Replace(",", ""));
                                        Info.COD_DRAWEE_ACCT = fields[6].Trim();
                                        Info.NAM_CUST_FULL = fields[7].Trim();
                                        Info.REF_INSTR_NO_REJECT = fields[8].Trim();
                                        //Info.AMT_TXN_LCY = Convert.ToDouble(fields[9].Trim(),ci);
                                        Info.AMT_TXN_LCY = fields[9].Trim() == "" ? 0 : Convert.ToDouble(fields[9].Trim().Replace(",", ""));
                                        Info.COD_DHIB_STAT = fields[10].Trim();
                                        Info.DAT_NSF_REJ = Convert.ToDateTime(fields[11].Trim());
                                        Info.COD_ORG_BRN = fields[12].Trim();
                                        Info.CUST_ADDRESS = ""; //fields[13].Trim();
                                        Info.CUST_PHONE = ""; //fields[14].Trim();
                                        Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                        Info.ENTRY_DATE = ProcessingDate();
                                        Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                        Info.UPDATE_DATE = ProcessingDate();

                                        bllFile.Save(Info);
                                    }
                                    catch (Exception ex)
                                    {
                                        ErrMessage += "<br>" + GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                                        ErrMessage += "<br>" + ex.Message;
                                    }
                                }
                                else
                                {
                                    ErrLine = i;
                                    i = rows.Length;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage += "<br><br>" + GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        ErrMessage += "<br>" + ex.Message;
                    }

                    File.Delete(fName);
                    AddLog("UPLOAD", "UPLOAD NEGATIVE FILE");

                    if (ErrMessage == "")
                    {
                        msg = this.GetGlobalResourceObject("Messages", "UploadSuccessAlert").ToString();
                        lblStatus.Text = msg;
                        FileUpLoadValidator.Visible = false;
                        AlertAndRedirect(msg, "negative_list.aspx");
                    }
                    else
                    {
                        lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                        FileUpLoadValidator.Visible = false;
                    }
                }
                else
                {
                    msg = this.GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                    lblStatus.Text = msg;
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("negative_list.aspx");
        }
    }
}
